import {
  get,
  post
} from './https'
import {
  formatTime
} from './tools'
export {
  formatTime
}

export let isDevelop = /^192\.168\..*8080$/.test(location.host)
export let baseUrl = '' // proxy 'config/index.js'

/**
 *
 * @param {base64字符串} urlData
 * @param {文件名} fileName
 */
const base64ToFile = (urlData, fileName = 'img.png') => {
  let arr = urlData.split(',')
  let mime = arr[0].match(/:(.*?);/)[1]
  let bytes = atob(arr[1]) // 解码base64
  let n = bytes.length
  let ia = new Uint8Array(n)
  while (n--) {
    ia[n] = bytes.charCodeAt(n)
  }
  return new File([ia], fileName, {
    type: mime
  })
}

/**
 *
 * 调起API获取图片
 * @param {最大图片数} maxCount
 */
const chooseImage = async (maxCount = 1) => {
  return new Promise(resolve => {
    window.sc && window.sc.chooseImage({
      count: maxCount,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera']
    },
    function (res) {
      const files = res.data
      const list = []
      // 处理拿到的base64数据
      for (let index = 0; index < files.length; index++) {
        let o = files[index]
        let base64 = `data:image/png;base64,${o}`
        list.push({
          url: base64
        })
      }
      resolve(list)
    }
    )
  })
}

/**
 *
 * 模拟上传图片的方法
 * @param {file格式的参数} param
 */
const uploadImage = async param => {
  return new Promise(resolve => {
    setTimeout(resolve({
      url: param.name || ''
    }), 1000)
  })
}

/**
 * 本地图片处理方法：
 *
 * 默认传入图片子组件的方法
 * 1 方法作用
 * 调起APP的选择图片API，拿到base64文件，并做返显 files:  = [{ url: base64 }]
 * 2 组件内方法返回的格式
 * let { success, data: files, message } = await this.uploadFn();
 */
export const uploadFn = async () => {
  let res = {}
  let isDevelop = /^192\.168\..*808.$/.test(location.host)
  if (isDevelop) {
    res = new Promise(resolve => {
      let imgStr = 'iVBORw0KGgoAAAANSUhEUgAAAC8AAAAuCAYAAAC4e0AJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAABnSURBVGhD7dmxDcAgDABBwzJhyzBmtoHGEkUGeCz9NXb5hTu39T4riuo5SzKe8r/5+eVymTlyOTwbivEU4ynGU4ynGE8xnmI8xXiK8RTjKcZTjKcYTzGeYjzFeIrxlNLxfsApxjMiNuvECkZnkue8AAAAAElFTkSuQmCC'
      setTimeout(
        resolve({
          success: true,
          message: 'local mock success!',
          data: {
            url: `data:image/png;base64,${imgStr}`
          }
        }),
        1000
      )
    })
  } else {
    // 调起API获取图片
    let files = await chooseImage()
    console.log('调起获取图片API....', files)
    // 返回的base64数据转文件
    res = {
      success: true,
      message: 'success!',
      data: files
    }
  }
  return res
}

/**
 * 文件上传图片：
 *
 * 提交表单时 先上传图片到服务器
 * 拿到返回的url参数
 * 注意：第三方方法 uploadImage 是单文件上传接口时 最好用并发上传
 * 注意：第三方方法 uploadImage 可接受多文件上传时 一次上传即可
 *
 */
export const uploadImgs = async (files = [{
  url: 'base64'
}], multiple = true) => {
  // 单文件并发上传时 urlList 为promise数组
  let urlList = []
  // 创建FormData 把本地base64数据转为文件流 获取云上文件的url
  if (multiple) {
    let _urlList = []
    for (let index = 0; index < files.length; index++) {
      let param = new FormData()
      let base64 = files[index].url
      let imgFile = base64ToFile(base64, 'img.png')
      param.append('file', imgFile)
      let url = uploadImage(param)
      _urlList.push(url)
    }
    urlList = await Promise.all(_urlList)
  } else {
    let param = new FormData()
    for (let index = 0; index < files.length; index++) {
      let imgFile = base64ToFile(files[index].url, 'img.png')
      param.append('file', imgFile)
    }
    urlList = await uploadImage(param)
  }
  return urlList
}

export const getDictList = (param) => {
  return post(`${baseUrl}`)
}

/**
 *
 * 添加字典
 * @param {*} param
 */
export const addDict = (param) => {
  return post(`${baseUrl}/dict/add/`, param)
}

/**
 *
 * 字典详情
 * @param {id} id
 */
export const getDetail = (id) => {
  return get(`${baseUrl}/dict/detail/`, id)
}
